﻿using System;
using System.Linq;
using Shell.PocoDot.Configurations;

namespace Shell.PocoDot
{
    public class EfDataContextFactory : IDataContextFactory
    {
        public virtual IDataContext<TPocoDot> Create<TPocoDot>() where TPocoDot : PocoDotBase
        {
            var t = typeof(TPocoDot);
            var registrar = PocoDotRegistrar.Registrar;
            var config = this.GetProvider<TPocoDot>();
            return new EfDataContext<TPocoDot>(config);
        }

        protected virtual ProviderConfiguration GetProvider<TPocoDot>()
            where TPocoDot : PocoDotBase
        {
            var configs = PocoDotRegistrar.Registrar.Configurations;
            var type = typeof(TPocoDot);
            var config = configs.SingleOrDefault(c => c.PocoDot == type);
            if (config == null)
            {
                throw new InvalidOperationException(SR.Get("Error.PocoConfigurationNotExist", type.Name));
            }
            return config.Provider;
        }
    }
}
